package dlb.busstop.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import dlb.busstop.data.Bus;
import dlb.busstop.data.BusinessObjectFactory;
import dlb.busstop.utils.ServiceProvider;

public abstract class BusListGrabber {

	public static BusListGrabber getInstance(JSONParser parser, ServiceProvider provider){
		return new BusListGrabberImpl(parser, provider);
	}
	
	public static BusListGrabber getInstance(JSONParser parser){
		
		return getInstance(parser, ServiceProvider.getInstance());
	}
	
	public abstract JSONArray grabBusJSONArray(String stopId) throws JSONException, IOException;

	public abstract List<Bus> grabBusList(String stopId) throws JSONException, IOException;
	
	static class BusListGrabberImpl extends BusListGrabber {

		private JSONParser parser;
		private ServiceProvider provider;

		public BusListGrabberImpl(JSONParser parser, ServiceProvider provider) {
			this.parser = parser;
			this.provider = provider;
		}

		@Override
		public JSONArray grabBusJSONArray(String stopId) throws JSONException, IOException {
			String url = provider.getProtocol() + "://" + provider.getHost()
					+ ":" + provider.getPort() + "/"
					+ provider.getResourceUrl() + "/GetStopInfoByID?"
					+ "stopid=" + stopId + "&psw=" + provider.getPassword();
			JSONObject rawJson = parser.parse(url);
			if (rawJson.get("d").equals(JSONObject.NULL)) {
				return null;
			}
			return rawJson.getJSONArray("d");
		}

		@Override
		public List<Bus> grabBusList(String locationId) throws JSONException, IOException {
			JSONArray busArray = grabBusJSONArray(locationId);
			if (busArray == null) {
				return null;
			}
			int length = busArray.length();
			List<Bus> buses = new ArrayList<Bus>(length);
			JSONObject busJson;
			Bus bus;
			for (int i = 0; i < length; i++) {
				busJson = busArray.getJSONObject(i);
				bus = BusinessObjectFactory.createBusFromJSON(busJson);
				buses.add(bus);
			}
			return buses;
		}

	}

}
